import { CSSProperties, ForwardedRef, forwardRef, useEffect, useImperativeHandle, useRef } from "react";
import { Terminal as XTerminal } from "xterm";
import { FitAddon } from "xterm-addon-fit";
import "xterm/css/xterm.css";
import './index.scss'
import { io, Socket } from "socket.io-client";
import { SafeAny } from "../../core/types/Safe";
import { baseUrl } from "../../common/constants";

export interface IReactTerminalRef {
    writeTerminal: (data: string) => void;
}

const Terminal = forwardRef((_props: SafeAny, ref: ForwardedRef<IReactTerminalRef>) => {
    const terminalRef = useRef(null); // DOM 容器引用
    const terminalInstance = useRef<XTerminal | null>(null); // Terminal 实例
    const socketRef = useRef<Socket | null>(null);

    useImperativeHandle(ref, () => {
        return {
            writeTerminal: (data: string) => {
                if (terminalInstance.current) {
                    socketRef.current?.emit("message", data)
                }
            },
        };
    }, [socketRef]);

    useEffect(() => {
        // 初始化终端
        const terminal = new XTerminal({
            fontFamily: 'monospace, "Courier New", "Microsoft YaHei", "WenQuanYi Micro Hei"',
            cursorBlink: true,
            fontSize: 10,
            theme: {
                background: "#1E1E1E",
                foreground: "#FFFFFF",
            },
        });
        // 初始化 FitAddon
        const fit = new FitAddon();
        terminal.loadAddon(fit);

        // 将终端附加到 DOM
        if (terminalRef.current) {
            terminal.open(terminalRef.current);
            fit.fit(); // 调整终端大小以适应容器
        }
        // 连接到 WebSocket Gateway
        const socket = io(baseUrl); // NestJS WebSocket 服务

        socket.on("connect", () => {
            terminal.writeln("Connected to local terminal.\n");
        });

        socket.on("output", (data: string) => {
            terminal.write(data.replace(/\n/g, '\r\n'));
        });

        socket.on("disconnect", () => {
            terminal.writeln("\nDisconnected from terminal.");
        });

        // 将用户输入发送到 WebSocket
        terminal.onData((data) => {
            socket.emit("message", data);
        });
        // 监听窗口大小变化并重新适配
        const handleResize = () => {
            fit.fit();
        };
        window.addEventListener("resize", handleResize);

        // 清理资源
        terminalInstance.current = terminal;
        socketRef.current = socket;
        return () => {
            window.removeEventListener("resize", handleResize);
            terminal.dispose();
            socket.disconnect();
        };
    }, []);

    // 容器样式
    const terminalStyle: CSSProperties = {
        width: "100%",
        height: "100%",
        // overflow: "hidden",
        display: "flex",
        flexDirection: "column",
        backgroundColor: "#181E29",
    };

    return <div className="terminal-container flex-center"> <div ref={terminalRef} style={terminalStyle} /></div>;
});

export default Terminal;
